package com.nami.gchat.infra.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nami.gchat.infra.cache.grpmember.GrpMemberCache;
import com.nami.gchat.domain.model.co.GrpMemberModel;
import com.nami.gchat.domain.repository.GrpMemberRepository;

import com.nami.gchat.infra.cache.grpmember.GrpSingleMemberCache;
import com.nami.gchat.infra.convertor.GrpMemberConvert;
import com.nami.gchat.infra.mapper.GroupMemberMapper;
import com.nami.gchat.infra.orm.GroupMemberDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class GrpMemberRepositoryImpl implements GrpMemberRepository {

    private final GroupMemberMapper baseMapper;

    @Override
    public List<GrpMemberModel> getGrpMembers(String grpId) {
        if (StringUtils.isBlank(grpId)) {
            return null;
        }
        List<GroupMemberDO> groupMembers = baseMapper.selectList(new LambdaQueryWrapper<GroupMemberDO>().eq(GroupMemberDO::getGroupId, grpId));
        return GrpMemberConvert.INSTANCE.convertList(groupMembers);
    }

    @Override
    public GrpMemberModel getGrpMember(String grpId, String userId) {
        if (StringUtils.isBlank(grpId) || StringUtils.isBlank(userId)) {
            return null;
        }
        GroupMemberDO groupMemberDO = baseMapper.selectOne(new LambdaQueryWrapper<GroupMemberDO>()
            .eq(GroupMemberDO::getGroupId, grpId)
            .eq(GroupMemberDO::getUserId, userId));
        return GrpMemberConvert.INSTANCE.convert(groupMemberDO);
    }

    @Override
    public List<GrpMemberModel> getGrpMembersFromCacheOrDB(String grpId) {
        List<GrpMemberModel> members = GrpMemberCache.getGrpMembers(grpId);
        if (members == null) {
            members = this.getGrpMembers(grpId);
            if (members == null) {
                return null;
            }
            GrpMemberCache.add(grpId, members);
            return GrpMemberCache.getGrpMembers(grpId); // 有没有可能竞争激烈放进去 再取出来为空
        }
        return members;
    }

    @Override
    public GrpMemberModel getGrpMemberFromCacheOrDB(String grpId, String userId) {
        GrpMemberModel grpMember = GrpSingleMemberCache.getGrpMember(grpId, userId);
        if (grpMember == null) {
            grpMember = this.getGrpMember(grpId, userId);
            if (grpMember == null) {
                return null;
            }
            GrpSingleMemberCache.add(grpMember);
            return grpMember.clone();
        }
        return grpMember;
    }


}
